package com.kinyx.framework.db.configs;

import java.util.HashMap;
import java.util.Map;

import com.kinyx.framework.Configs;
import com.kinyx.framework.db.dialect.Dialect;
import com.kinyx.framework.enums.impl.ErrorCodeX;
import com.kinyx.framework.exception.KRuntimeException;
import com.kinyx.framework.reflect.KBeanUtils;
import com.kinyx.framework.reflect.KClassScanner;

/**
 * 数据库配置工具类
 */
public class DBConfigsHelper {

	/** 是否已经初始化过 */
	private static boolean inited = false;
	/** 数据库方言实现类 */
	private static Map<String, Dialect> dialects = new HashMap<>();
	/** 数据库配置实现类 */
	private static Map<String, DBConfigs> configs = new HashMap<>();

	private static void handleConfig(final DBConfigs config) {
		config.setProperties(config.getConfigsFileName(), null, null, null);
		config.afterPropertiesSet();
		configs.put(config.getKey(), config);
	}

	public static DBConfigs getDBConfigs(final String key) {
		if (!inited) {
			// 数据库方言实现类
			KBeanUtils.newInstances(KClassScanner.scanClasses(Dialect.class, "com.kinyx.framework.db.dialect", true, false)).forEach(dialect -> {
				dialects.put(dialect.name(), dialect);
			});
			// 数据库配置实现类
			KBeanUtils.newInstances(KClassScanner.scanClasses(DBConfigs.class, "com.kinyx.framework.db.configs", true, false)).forEach(config -> {
				handleConfig(config);
			});
			if (Configs.FRAMEWORK_DEBUG) {// 测试环境下增加测试用配置
				handleConfig(new DBConfigs() {
					@Override
					public String getKey() { return null; }
					@Override
					protected String getConfigsFileName() { return "configs-demo.properties"; }
				});
			}
			inited = true;
		}
		return configs.get(key);
	}

	static Dialect getDialectByDriverClassName(final String driverClassName) {
		if (driverClassName == null) { return null; }
		for (final Dialect dialect : dialects.values()) {
			if (dialect.checkDriverClassName(driverClassName)) {
				return dialect;
			}
		}
		throw new KRuntimeException(ErrorCodeX.NotImplemented);
	}

}
